﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ReferralTracker.Data.Entities;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Net;

namespace ReferralTracker.Helpers {
    public class ReferralTrackerApiProxy {

        HttpRequestBase _request = null;

        public ReferralTrackerApiProxy(HttpRequestBase request) {
            _request = request;
        }

        public HttpResponseMessage AddReferral(Referral referral) {
            var referralModel = new {
                ReferralId = referral.User.UserDetail.ReferralId,
                ReferralType = referral.IdReferralType,
                ReferralLink = referral.ReferralLink,
                ClientIPAddress = referral.ClientIPAddress
            };
            var rootUrl = (new Uri(referral.ReferralLink)).GetLeftPart(UriPartial.Authority);
            var baseUri = new Uri(rootUrl);
            HttpClient client = null;

            if (_request.Cookies.Count > 0) {
                var requestCookies = new CookieContainer();
                var handler = new HttpClientHandler() {
                    UseCookies = true,
                    CookieContainer = requestCookies
                };

                foreach (var key in _request.Cookies.AllKeys) {
                    var item = _request.Cookies[key];
                    var cookie = new Cookie() {
                        Name = item.Name,
                        Value = item.Value,
                        Path = item.Path,
                        Expires = item.Expires
                    };

                    requestCookies.Add(baseUri, cookie);
                }

                client = new HttpClient(handler) {
                    BaseAddress = baseUri
                };
            }
            else {
                client = new HttpClient() {
                    BaseAddress = baseUri
                };
            }

            var response = client.PostAsJsonAsync("api/referral", referralModel).Result;

            response.EnsureSuccessStatusCode();

            return response;
        }

    }
}